/**
 * Copyright (C) 2018-2022
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
/**
 * openIM JS文档 https://doc.rentsoft.cn/#/js_v2/sdk_integrate/sdk_use
 */

import api from '@/utils/api'
import {
	OpenIMSDK
} from "@/public/open-im-sdk/index.js";

//初始化
const initIMdata = () => {
	const systemInfo = uni.getSystemInfoSync();
	let globalData = getApp().globalData;
	let IMdata = globalData.IMdata;
	// IMdata.IMOpenLog = true; //im日志
	IMdata.IMoperationID = systemInfo.deviceId;
	IMdata.IMuserID = '';
	IMdata.IMtoken = '';
	IMdata.IMJSwsAddr = '';
	IMdata.IMloginStatus = false;
	IMdata.IMconnectStatus = 0; // 服务器连接状态:0,:失败;1:成功;2:连接中
	IMdata.IMmessageList = []; // 会话列表
	IMdata.IMheartCheckTimer = null;
	IMdata.IMcheckIMLoginOK = true; //监听IM是否连接
	globalData.JIM = new OpenIMSDK()
}

// initIM let globalData = getApp().globalData
const initOpenIM = () => {
	// 如果是连接中就直接返回
	let IMdata = getApp().globalData.IMdata
	if (IMdata.IMOpenLog) console.log('initOpenIM--------', IMdata)
	if (IMdata.IMconnectStatus == 2) {
		return new Promise((resolve, reject) => {
			resolve("success");
		})
	} else {
		initIMdata()
		return new Promise((resolve, reject) => {
			IMdata.checkIMLoginOK = true
			requestIMToken().then((res) => {
				initIM().then(() => {
					getSelfUserInfo()
					heartCheck() //IM连接心跳
					addListener() //消息监听
					updateTotalUnreadMsgCount() //更新会话未读总数
					resolve("success");
				}).catch(e => {
					reject();
				})
			})
		})
	}

}

const initIM = () => { // 通过web获取IM的Token,然后进行连接IM服务器
	let globalData = getApp().globalData
	let IMdata = globalData.IMdata
	const config = {
		userID: IMdata.IMuserID,
		token: IMdata.IMtoken,
		url: IMdata.JSwsAddr,
		platformID: IMdata.IMplatform,
	};
	if (IMdata.IMOpenLog) console.log("OpenIM------登录IM服务器", config)
	IMdata.IMconnectStatus = 2 //连接中
	return new Promise((resolve, reject) => {
		// 判断是否有保存的用户信息，如果有就自动登录im，没有就直接返回不进行任何操作
		let userInfo = uni.getStorageSync('user_info')
		// 如果没有用户信息，或者imToken为空，直接返回
		if (!userInfo || !userInfo.id || IMdata.IMloginStatus) {
			resolve()
			return
		}
		globalData.JIM.login(config).then((res) => {
			// 启动事件监听
			let globalData = getApp().globalData
			if (IMdata.IMOpenLog) console.log("OpenIM------连接成功**********");
			globalData.IMdata.IMloginStatus = true
			globalData.IMdata.IMconnectStatus = 1 //连接成功
			uni.$emit('JIMLogin')
			resolve()
		}).catch((err) => {
			if (IMdata.IMOpenLog) console.log("OpenIM------连接错误", JSON.stringify(err));
			// IM连接已关闭
			if (err.errCode == 111 || err.errCode == 112) {
				if (IMdata.IMOpenLog) console.log("OpenIM------连接关闭或连接错误--开始重连");
				//服务器连接状态:0,:失败;1:成功;2:连接中
				IMdata.IMconnectStatus = false
				IMdata.IMconnectStatus = 0 //连接失败
				reloginIM()
				reject()
			} else {
				if (err.errCode != 1002) {
					IMdata.IMloginStatus = false
					IMdata.IMconnectStatus = 2 //连接中
				}
				checkLoginStatus().then(res => {
					// 启动事件监听
					let globalData = getApp().globalData
					if (IMdata.IMOpenLog) console.log("OpenIM------连接成功**********");
					globalData.IMdata.IMloginStatus = true
					globalData.IMdata.IMconnectStatus = 1 //连接成功
					uni.$emit('JIMLogin')
					resolve()
				})
			}
		});
	})
}

const requestIMToken = () => { // 通过web获取IM的Token,然后进行连接IM服务器
	let userInfo = uni.getStorageSync('user_info')
	let thirdSession = uni.getStorageSync('third_session')
	let globalData = getApp().globalData
	let IMdata = globalData.IMdata
	return new Promise((resolve, reject) => {
		//还不是商城用户，不登录JLIM
		if (!userInfo || !userInfo.id || !thirdSession) {
			if (IMdata.IMOpenLog) console.log("还不是商城用户，不登录IM")
			resolve("success");
			return
		}
		api.imLogin({
			operationID: IMdata.IMoperationID,
			platform: IMdata.IMplatform,
			userID: GetIMuserID()
		}).then(res => {
			IMdata.IMconnectStatus = 2 //连接中
			// 101:登录成功 102:登陆中 103:登录失败 201:登出
			if (res.errCode === 0) {
				if (IMdata.IMOpenLog) console.log('IM获取webToken成功--开始连接IM服务器', res.data);
				// 登录成功-保存im要用的数据
				IMdata.JSwsAddr = "wss://" + res.url + "/jssdk/"
				IMdata.IMtoken = res.data.token
				IMdata.IMuserID = res.data.userID
				resolve("success");
			} else {
				if (IMdata.IMOpenLog) console.log('登录webIM失败3---', res);
				reject();
			}
		}).catch(e => {
			if (IMdata.IMOpenLog) console.log('登录webIM错误4---', e);
			reject();
		});
	})
}


//获取IM用户信息
const getSelfUserInfo = (userInfo) => {
	// 当获取用户信息失败时需要进行注册
	return new Promise((resolve, reject) => {
		let globalData = getApp().globalData
		globalData.JIM.getSelfUserInfo().then((res) => {
			if (res.errCode === 0) {
				const data = JSON.parse(res.data);
				if (globalData.IMdata.IMOpenLog) console.log("OpenIM------获取IM用户信息成功");
				globalData.IMdata.IMuserID = data.userID
			} else {
				if (globalData.IMdata.IMOpenLog) console.error('OpenIM------获取IM用户信息错误: ' + res)
			}
			resolve()
		}).catch(err => {
			if (err.errCode == 802) { //未注册
				registerIM().then(() => {
					if (globalData.IMdata.IMOpenLog) console.log('OpenIM------注册成功-重新登录')
					//注册成功后退出用户重新进行登录
					// globalData.IMdata.IMloginStatus = true
					// reloginIM()
				})
			}
			reject()
		});
	})

}

// 修改IM用户信息,更新用户昵称，头像等
const updateIMuserInfo = (userInfo) => {
	// 当获取用户信息失败时需要进行注册
	let globalData = getApp().globalData
	const selfInfo = {
		userID: globalData.IMdata.IMuserID,
		faceURL: userInfo.headimgUrl,
		gender: userInfo.sex ? Number(userInfo.sex) : 0,
		nickname: userInfo.nickName,
		phoneNumber: userInfo.phone,
	}
	globalData.JIM.setSelfInfo(selfInfo).then(({
		data
	}) => {
		if (globalData.IMdata.IMOpenLog) console.log('OpenIM------更新IM用户信息成功 ')
	}).catch(err => {
		if (globalData.IMdata.IMOpenLog) console.log('OpenIM------更新IM用户信息失败', err)
	})
}

// 注册IM用户
const registerIM = () => {
	let globalData = getApp().globalData
	if (globalData.IMdata.IMOpenLog) console.log('OpenIM------注册IM用户start');
	return new Promise((resolve, reject) => {
		//获取用户信息
		let userInfo = uni.getStorageSync('user_info')
		let thirdSession = uni.getStorageSync('third_session')
		if (!userInfo || !userInfo.id || !thirdSession) {
			if (globalData.IMdata.IMOpenLog) console.log("OpenIM------还不是商城用户，不登录IM")
			reject();
			return
		}
		const options = {
			faceURL: userInfo.headimgUrl,
			gender: userInfo.sex,
			nickname: userInfo.nickName,
			phoneNumber: userInfo.phone,
			operationID: globalData.IMdata.IMoperationID,
			platform: globalData.IMdata.IMplatform,
			userID: globalData.IMdata.IMuserID, //为保证用户ID唯一，IM用户ID=租户ID+用户ID 组成
		}
		if (globalData.IMdata.IMOpenLog) console.log("OpenIM------注册IM用户", options)
		// 字段说明：https://doc.rentsoft.cn/#/v2/description/fields
		api.imRegister(options).then(res => {
			//注册后更新IMtoken
			if (globalData.IMdata.IMOpenLog) console.log('OpenIM------注册IM用户----成功', res);
			if (res.errCode === 0) {
				// 更新IM要用的数据
				globalData.IMdata.IMtoken = res.data.token
				globalData.IMdata.IMuserID = res.data.userID
				resolve()
			}
		}).catch(e => {
			if (globalData.IMdata.IMOpenLog) console.log('OpenIM------注册IM失败', e);
			reject();
		});

	});
}

//重新登录
const reloginIM = () => {
	let globalData = getApp().globalData
	if (globalData.IMdata.IMconnectStatus != 0 || globalData.IMdata.IMloginStatus) { //防止重复登录
		return
	}
	//如果重新登录需要关闭心跳
	if (globalData.IMdata.IMheartCheckTimer) clearInterval(globalData.IMdata.IMheartCheckTimer)
	if (globalData.IMdata.IMOpenLog) console.log("OpenIM------重新登录IM**********");
	globalData.IMdata.IMloginStatus = false
	globalData.IMdata.IMconnectStatus = 0
	//退出重新登录
	IMloginOut().then((res) => {
		if (!globalData.IMdata.IMloginStatus && globalData.IMdata.IMconnectStatus == 0) { //防止重复登录
			//重新初始化登录
			initOpenIM()
		} else {
			if (globalData.IMdata.IMOpenLog) console.log("OpenIM------重新登录IM成功**********");
		}
	})
}

// 兼容之前的JIM
const getJIMUnreadMsgCnt = () => {
	updateTotalUnreadMsgCount()
}

// IM登录成功后自动 获取未读消息总数
// 监听事件中也会自动更新
const updateTotalUnreadMsgCount = () => {
	let globalData = getApp().globalData
	if (globalData.IMdata.IMOpenLog) console.log('OpenIM------更新IM会话总数');
	if (globalData.JIM) {
		uni.$emit('JIMConversation')
		globalData.JIM.getTotalUnreadMsgCount().then(({
			data
		}) => {
			if (data && data > 0) {
				uni.setTabBarBadge({
					index: 2,
					text: data + ''
				});
			} else {

				uni.removeTabBarBadge({
					index: 2
				});
			}
		}).catch(err => {

		})
	}
}

// JS sdk 使用webSocket 在小程序和APP容易掉线，所以自己维护了一份心跳检测
const heartCheck = () => {
	let globalData = getApp().globalData
	let timeout = 30000; //30秒
	if (globalData.IMdata.IMOpenLog) console.log("IM心跳检测登录状态-开始")
	if (globalData.IMdata.IMheartCheckTimer) clearInterval(globalData.IMdata.IMheartCheckTimer)
	globalData.IMdata.IMheartCheckTimer = setInterval(() => {
		checkLoginStatus().then((res) => {
			if (globalData.IMdata.IMOpenLog) console.log("IM心跳检测登录状态-在线", res)
		}).catch(err => {
			if (globalData.IMdata.IMOpenLog) console.log("IM心跳检测登录状态-掉线了-重新登录", err)
			if (err.errCode == 112) { // ws conecting...

			} else {}
			// uni.$emit('JIMDisconnect')
			// globalData.IMdata.IMconnectStatus = 0
			// reloginIM()
		})
	}, timeout);
}

const checkLoginStatus = () => {
	return new Promise((resolve, reject) => {
		let globalData = getApp().globalData
		if (globalData.IMdata.IMOpenLog)
			console.log('OpenIM------检查登录状态(101:登录成功 102:登陆中 103:登录失败 201:登出)')
		globalData.IMdata.IMcheckIMLoginOK = false //10秒内检查登录是否正常，不正常就表示已经断开连接了
		setTimeout(() => {
			if (!globalData.IMdata.IMcheckIMLoginOK) { //启动重连
				if (globalData.IMdata.IMOpenLog)
					console.log("连接超时监测10秒未响应---启动重连");
				globalData.IMdata.IMloginStatus = false
				globalData.IMdata.IMconnectStatus = 0
				uni.$emit('JIMDisconnect')
				reloginIM()
			}
		}, 10000)
		globalData.JIM.getLoginStatus().then(res => {
			globalData.IMdata.IMcheckIMLoginOK = true
			let loginStatus = res.data
			if (globalData.IMdata.IMOpenLog) console.log('OpenIM------获取登录状态为:' + loginStatus);
			if (loginStatus == 103) { //自动重新登录
				globalData.IMdata.IMloginStatus = false
				globalData.IMdata.IMconnectStatus = 0
				uni.$emit('JIMDisconnect')
				reloginIM()
				reject(globalData.IMdata.IMloginStatus)
			} else if (loginStatus == 102) { //
				globalData.IMdata.IMloginStatus = true
				globalData.IMdata.IMconnectStatus = 2
				resolve(globalData.IMdata.IMloginStatus)
			} else if (loginStatus == 101) { //
				globalData.IMdata.IMloginStatus = true
				globalData.IMdata.IMconnectStatus = 1
				// uni.$emit('JIMLogin')
				resolve(globalData.IMdata.IMloginStatus)
			} else if (loginStatus == 201) { //
				globalData.IMdata.IMloginStatus = false
				globalData.IMdata.IMconnectStatus = 0
				uni.$emit('JIMDisconnect')
				reloginIM()
				reject(globalData.IMdata.IMloginStatus)
			} else {
				globalData.IMdata.IMloginStatus = false
				globalData.IMdata.IMconnectStatus = 0
				reloginIM()
				reject(globalData.IMdata.IMloginStatus)
			}
		}).catch(err => {
			let globalData = getApp().globalData
			globalData.IMdata.IMcheckIMLoginOK = true
			globalData.IMdata.IMloginStatus = false
			uni.$emit('JIMDisconnect')
			if (globalData.IMdata.IMOpenLog) console.log('OpenIM------获取登录状态err', err)
			if (err.errCode == 112 || globalData.IMdata.IMconnectStatus == 0) { //ws conecting...
				globalData.IMdata.IMconnectStatus = 0
				reloginIM()
			}
			reject(globalData.IMdata.IMloginStatus)
		})
	})

}

// 取消监听
const clearListener = () => {

	let globalData = getApp().globalData
	let openIM = globalData.JIM
	if (globalData.IMdata.IMOpenLog) console.log("OpenIM------清除已有监听事件")
	openIM.off("OnConnectSuccess")
	openIM.off("OnConnectFailed")
	openIM.off("OnConnecting")
	openIM.off("SendMessageProgress")
	openIM.off("SendMessageSuccess")
	openIM.off("SendMessageFailed")
	openIM.off("OnRecvNewMessage")
	openIM.off("OnRecvMessageRevoked")
	openIM.off("OnRecvC2CReadReceipt")
	openIM.off("UploadFileFailed")
	openIM.off("UploadFileProgress")
	openIM.off("UploadFileSuccess")
	openIM.off("OnNewConversation")
	openIM.off("OnConversationChanged")
	openIM.off("OnTotalUnreadMessageCountChanged")
}

// 设置监听
const addListener = () => {
	let globalData = getApp().globalData
	let openIM = globalData.JIM
	clearListener()
	if (globalData.IMdata.IMOpenLog) console.log("OpenIM------启动事件监听")
	// connect status
	openIM.on("OnConnectSuccess", (res) => {
		if (globalData.IMdata.IMOpenLog) console.log("onConnectSuccess", res);
		let connectStatus = globalData.IMdata.IMconnectStatus;
		if (connectStatus !== 1) { //之前不是连接状态的，重新登录连接IM
			globalData.IMdata.IMconnectStatus = 1
			checkLoginStatus()
			uni.$emit('JIMLogin')
		}
	});
	openIM.on("OnConnectFailed", (res) => {
		uni.$emit('JIMDisconnect')
		if (globalData.IMdata.IMOpenLog) console.log("onConnectFailed", res);
		const {
			errCode
		} = res;
		const kickedArr = [706, 1001];
		if (kickedArr.includes(errCode)) {
			if (globalData.IMdata.IMOpenLog) console.log("OpenIM------该账号已在另一设备登录");
			// toast("该账号已在另一设备登录");
			// setTimeout(() => {
			// 	reloginIM()
			// }, 1000);
		} else {
			globalData.IMdata.IMconnectStatus = 0
			setTimeout(() => {
				globalData.IMdata.IMloginStatus = false
				reloginIM()
			}, 3000);
			if (globalData.IMdata.IMOpenLog) console.log("服务器连接超时，请稍后再试");
		}
	});
	openIM.on("OnConnecting", (res) => {
		if (globalData.IMdata.IMOpenLog) console.log("onConnecting", res);
		const connectStatus = globalData.IMdata.IMconnectStatus;
		// if (connectStatus !== 2) {
		// store.commit("IMuser/set_connectStatus", 2);
		// }
	})
	// message listener 接收到消息
	openIM.on("OnRecvNewMessage", (res) => {
		if (globalData.IMdata.IMOpenLog) console.log("onRecvNewMessage", res);
		const m = JSON.parse(res.data);
		if (m.contentType !== 113) {
			const currentUserID = globalData.IMdata.IMuserID;
			const ChatUserID = currentUserID === m.sendID ? m.recvID : m.sendID;
			if (m) { // 消息保存到本地
				saveIMMsg([m], ChatUserID)
				//通知消息接收
				uni.$emit('JIMMsgChange', m)
			}
		}
	});
	openIM.on("OnNewConversation", (res) => {
		if (globalData.IMdata.IMOpenLog) console.log("onNewConversation", res); // 新增会话
		updateTotalUnreadMsgCount() //更新会话未读总数
	});
	openIM.on("OnConversationChanged", (res) => {
		if (globalData.IMdata.IMOpenLog) console.log("OnConversationChanged");
		// 会话更改
		updateTotalUnreadMsgCount() //更新会话未读总数
	});
	openIM.on("OnTotalUnreadMessageCountChanged", (res) => {
		if (globalData.IMdata.IMOpenLog) console.log("OnTotalUnreadMessageCountChanged", res);
		if (res.errCode == 0) {
			uni.setTabBarBadge({
				index: 2,
				text: res.data + ''
			});
		}
	});
	// 个人用户信息修改
	openIM.on("OnSelfInfoUpdated", (res) => {
		if (globalData.IMdata.IMOpenLog) console.log('个人用户信息修改', res);
		if (res.errCode == 0) {
			// store.commit("IMuser/set_userInfo", JSON.parse(res.data));
		}
	});
	if (globalData.IMdata.IMOpenLog) console.log("OpenIM------登录IMend")
}


//退出登录
const IMloginOut = () => {
	return new Promise((resolve, reject) => {
		let globalData = getApp().globalData
		if (globalData.IMdata.IMOpenLog) console.log("OpenIM------退出登录IM开始");
		if (globalData.IMdata.IMheartCheckTimer) clearInterval(globalData.IMdata.IMheartCheckTimer)
		// uni.$emit('JIMDisconnect') //发送连接已断开通知
		globalData.JIM.logout().then(res => {
			initIMdata()
			clearListener()
			if (globalData.IMdata.IMOpenLog) console.log("OpenIM------退出登录IM成功");
			resolve()
			return
		})
		// 退出超时则强制清空返回
		setTimeout(() => {
			if (globalData.IMdata.IMconnectStatus == 0) {
				initIMdata()
				clearListener()
				if (globalData.IMdata.IMOpenLog) console.log("OpenIM------强制退出登录IM**********");
				resolve()
			}
		}, 5000)
	})

}
//删除会话
const deleteConversation = (conversation) => {
	let conversationID = conversation.conversationID
	const currentUserID = GetIMuserID();
	//当前登录人的key+聊天对象的ID组成保存聊天数据的key然后保存 用一对一聊天的id作为key,
	let conversationLocalSaveKey = "conversation_list" + currentUserID;
	let list = uni.getStorageSync(conversationLocalSaveKey);
	if (list && list.length > 0) {
		let index = -1
		for (var i = 0; i < list.length; i++) {
			if (list[i].conversationID == conversationID) {
				index = i
				break
			}
		}
		if (index >= 0) {
			let newList = list.splice(index, 1)
			saveConversationList(newList)
			//删除本地聊天
			const currentUserID = GetIMuserID();
			// 当前登录人的key+聊天对象的ID组成保存聊天数据的key然后保存 用一对一聊天的id作为key,
			let chatRecordLocalSaveKey = "chat_record_" + currentUserID + conversation.userID;
			uni.removeStorageSync(chatRecordLocalSaveKey)
		}
	}
}
// 保存会话列表
const saveConversationList = (list) => {
	const currentUserID = GetIMuserID();
	//当前登录人的key+聊天对象的ID组成保存聊天数据的key然后保存 用一对一聊天的id作为key,
	let conversationLocalSaveKey = "conversation_list" + currentUserID;
	uni.setStorageSync(conversationLocalSaveKey, JSON.stringify(list));
}
// 获取会话列表
const getConversationList = () => {
	const currentUserID = GetIMuserID();
	//当前登录人的key+聊天对象的ID组成保存聊天数据的key然后保存 用一对一聊天的id作为key,
	let conversationLocalSaveKey = "conversation_list" + currentUserID;
	let list = uni.getStorageSync(conversationLocalSaveKey);
	return list ? JSON.parse(list) : []
}
// 保存会话的聊天消息列表记录，离线消息时使用
// 保存消息到本地(1.先取出消息，2.然后保存消息到对应的时间)用于离线消息
const saveIMMsg = (messages, ChatUserID) => {
	// 消息对象
	// https://doc.rentsoft.cn/#/js_v2/sdk_integrate/struct?id=%e6%b6%88%e6%81%af%e5%af%b9%e8%b1%a1
	const currentUserID = GetIMuserID();
	// 当前登录人的key+聊天对象的ID组成保存聊天数据的key然后保存 用一对一聊天的id作为key,
	let chatRecordLocalSaveKey = "chat_record_" + currentUserID + ChatUserID;
	// 取出保存的聊天数据
	let localMsgStr = uni.getStorageSync(chatRecordLocalSaveKey) // 本地消息
	let localMsgArray = localMsgStr ? JSON.parse(localMsgStr) : [] // 消息数组
	let localMsgIds = []
	localMsgIds = localMsgArray.map(itemId => {
		return itemId.clientMsgID
	})
	// 插入聊天数据
	for (var i = 0; i < messages.length; i++) { // 服务器记录与本地保存的记录比对 保存到本地
		// 服务器记录与本地保存的记录比对
		// 云端的记录 时间1 时间2
		// 本地 时间0 时间3
		// 保证记录完整，聊天界面查看时以本地数据为准
		let curMsg = messages[i]
		let curIndex = -1;
		let localMsgArrayLength = localMsgArray.length - 1;
		if (localMsgArray.length > 0 && localMsgIds.indexOf(curMsg.clientMsgID) == -1) { //当前消息是否存在，如果不存在就插入
			if (curMsg.sendTime < localMsgArray[0].sendTime) { //插入到最前面
				curIndex = 0
			} else {
				localMsgArray.map((itemMsg, index) => {
					if (localMsgArrayLength == index) {
						curIndex = index
					} else if (curMsg.sendTime > itemMsg.sendTime && curMsg.sendTime <
						localMsgArray[index + 1].sendTime) {
						curIndex = index //插入到指定位置
						return
					}
				})
			}
		}
		if (localMsgArray.length > 0) {
			if (curIndex > -1) {
				if (localMsgArrayLength == curIndex) {
					localMsgArray.push(curMsg)
				} else {
					localMsgArray.splice(curIndex, 0, curMsg)
				}
			}
		} else {
			localMsgArray.push(curMsg)
		}
	}
	uni.setStorageSync(chatRecordLocalSaveKey, JSON.stringify(localMsgArray));
}


// 获取IM的客服ID //为保证用户ID唯一，IM用户ID=租户ID+"B"+用户ID 组成
const GetIMuserSerID = (cusSer) => {
	if (!cusSer || !cusSer.id) {
		return null
	}
	return cusSer.tenantId + 'B' + cusSer.id;
}
//获取IM的userID或创建IM的userID使用 //为保证用户ID唯一，IM用户ID=租户ID+"C"+用户ID 组成
const GetIMuserID = () => {
	let userInfo = uni.getStorageSync('user_info')
	if (!userInfo || !userInfo.id) {
		return null
	}
	return userInfo.tenantId + 'C' + userInfo.id;
}

// IM显示时间字符处理
const parseTimeMsg = (dateLong) => {
	let myDate = new Date(dateLong)
	var hour = myDate.getHours();
	var minutes = myDate.getMinutes();
	if (minutes < 10) minutes = '0' + minutes;
	return timeFormat(hour, myDate) + ' ' + hour + ':' + minutes;
}
const timeFormat = (hour, time) => {
	var hour = time.getHours();
	var minutes = time.getMinutes();
	var year = time.getYear(); //获取当前年份(2位)
	var month = time.getMonth() + 1; //获取当前月份(0-11,0代表1月)
	var day = time.getDate(); ////获取当前日(1-31)
	var thisDate = new Date();
	var thisyear = thisDate.getYear(); //获取当前年份(2位)
	var thismonth = thisDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
	var thisday = thisDate.getDate(); //获取当前日(1-31)
	if (year == thisyear && month == thismonth && day == thisday) {
		if (hour < 6) {
			return "凌晨";
		} else if (hour < 9) {
			return "早上";
		} else if (hour < 12) {
			return "上午";
		} else if (hour < 14) {
			return "中午";
		} else if (hour < 17) {
			return "下午";
		} else if (hour < 19) {
			return "傍晚";
		} else if (hour < 22) {
			return "晚上";
		} else {
			return "夜里";
		}
	} else {
		var date3 = thisDate.getTime() - time.getTime();
		// var years = Math.floor(date3 / (12 * 30 * 24 * 3600 * 1000));
		var years = thisyear - year;
		var leave = date3 % (12 * 30 * 24 * 3600 * 1000);
		var months = Math.floor(leave / (30 * 24 * 3600 * 1000));
		var leave0 = leave % (30 * 24 * 3600 * 1000);
		var days = Math.floor(leave0 / (24 * 3600 * 1000));
		if (years == 0 && months == 0 && days > 0 && days < 7) {
			switch (days) {
				case 1:
					return '昨天';
				case 2:
					return '前天';
				default:
					return "星期" + "日一二三四五六".charAt(time.getDay());
					break;
			}
		} else {
			if (months == 0 && years == 0 && days == 0) {
				return '昨天';
			}
			if (month < 10) month = '0' + month;
			if (day < 10) day = '0' + day;
			if (years == 0) {
				return month + '-' + day;
			} else {
				return time.getFullYear() + '-' + month + '-' + day;
			}
		}
	}
};

// IM使用的是JS websocket的，所以小程序和APP进入后台时非常容易断连
// 所以在进入后台后主动断开连接，重新进入页面后重新连接【如果有更好的处理连接的办法感谢进行工单分享一下(*^▽^*)】
// APP退出到后台20秒后自动退出IM，保证下次进入时可以连接上IM
const showAPP = () => {
	let globalData = getApp().globalData
	if (globalData.IMdata.IMOpenLog) console.log('APP进入前台-登录IM')
	if (globalData.hideAPPTimer) {
		clearTimeout(globalData.hideAPPTimer)
		globalData.hideAPPTimer = null
	} else {
		//重新连接
		reloginIM()
	}
}
// APP退出到后台20秒后自动退出IM
const hideAPP = () => {
	let globalData = getApp().globalData
	if (globalData.IMdata.IMOpenLog) console.log('APP退出到后台-20秒后退出IM')
	if (!globalData.hideAPPTimer) {
		if (globalData.IMdata.IMOpenLog) console.log('')
		globalData.hideAPPTimer = setTimeout(() => {
			globalData.hideAPPTimer = null
			if (globalData.IMdata.IMOpenLog) console.log('APP退出到后台-退出IM启动')
			IMloginOut()
		}, 20000)
	}
}
/**
 * 创建消息时用到的聊天UUID
 */
const chatMsgUUID = () => {
	return GetIMuserID() + new Date().getTime() + Math.floor(Math.random() * 8);
};
module.exports = {
	addListener,
	refreshConoversation: updateTotalUnreadMsgCount,
	getSelfUserInfo,
	updateIMuserInfo,
	checkLoginStatus,
	getJIMUnreadMsgCnt,
	heartCheck,
	initOpenIM,
	IMloginOut,
	reloginIM,
	showAPP,
	hideAPP,
	GetIMuserID,
	GetIMuserSerID,
	saveConversationList,
	getConversationList,
	deleteConversation,
	saveIMMsg,
	parseTimeMsg,
	chatMsgUUID,
}
